﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Diagnostics;
using Microsoft.SharePoint.Administration;

namespace SCCL2010
{
    public static class ErrorHandling
    {

        /// <summary>
        /// Method used for logging error message into Error List.
        /// </summary>
        /// <param name="cLocation"></param>
        /// <param name="cErrorDetails"></param>
        /// <param name="ex"></param>
        public static void HandleError(string cLocation, string cErrorDetails, Exception ex)
        {

            HandleError(SPContext.Current.Web, String.Format("{0} - {1}", cLocation, cErrorDetails), ex);

            
        }

        /// <summary>
        /// Method used for logging error message into Error List.
        /// </summary>
        /// <param name="cLocation"></param>
        /// <param name="ex"></param>
        public static void HandleError(string cLocation, Exception ex)
        {
            HandleError(SPContext.Current.Web, cLocation, ex);
            
        }

        /// <summary>
        /// Method used for logging error message into Error List.
        /// </summary>
        /// <param name="oTrargetWeb"></param>
        /// <param name="cLocation"></param>
        /// <param name="ex"></param>
        public static void HandleError(SPWeb oTrargetWeb, string cLocation, Exception ex)
        {
            LogError(String.Format("{0} {1}", cLocation, ex.Message));
            try
            {
                string cSiteURL = oTrargetWeb.Site.Url.ToLower();
                string cWebRel = oTrargetWeb.Url.ToLower().Replace(cSiteURL, "");
                if (cWebRel == cSiteURL) cWebRel = "/";
                SPSecurity.RunWithElevatedPrivileges(() =>
                {
                    using (SPSite oSite = new SPSite(cSiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb(cWebRel))
                        {
                            oWeb.AllowUnsafeUpdates = true;
                            SPList oList = oWeb.Lists["ErrorList"];
                            SPListItem item = oList.Items.Add();
                            item["Title"] = ex.Message;
                            item["Location"] = cLocation;
                            item["Stack Trace"] = ex.StackTrace;
                            item["User"] = oWeb.CurrentUser;
                            oWeb.AllowUnsafeUpdates = true;
                            item.Update();
                        }
                    }
                });
                LogError(String.Format("{0} - {1}", cLocation, ex.Message));
            }
            catch
            {

            }
        }

        /// <summary>
        /// Method used for logging error message into Error List.
        /// </summary>
        /// <param name="cWebURl"></param>
        /// <param name="cLocation"></param>
        /// <param name="cMessage"></param>
        public static void LogMessage(string cWebURl, string cLocation, string cMessage)
        {
            LogError(String.Format("{0} {1}", cLocation, cMessage));
            try
            {
                using (SPSite oSite = new SPSite(cWebURl))
                {
                    SPWeb oWeb = oSite.RootWeb;
                    oWeb.AllowUnsafeUpdates = true;
                    SPList oList = oWeb.Lists["ErrorList"];
                    SPListItem item = oList.Items.Add();
                    item["Title"] = cMessage;
                    item["Location"] = cLocation;
                    item["User"] = oWeb.CurrentUser;
                    oWeb.AllowUnsafeUpdates = true;
                    item.Update();
                    LogError(String.Format("{0} - {1}", cLocation, cMessage));
                }
            }
            catch
            {

            }
        }

        /// <summary>
        /// Method used for logging error message into Error List.
        /// </summary>
        /// <param name="oTrargetWeb"></param>
        /// <param name="cLocation"></param>
        /// <param name="cMessage"></param>
        public static void LogMessage(SPWeb oTrargetWeb, string cLocation, string cMessage)
        {
            try
            {
                string cSiteURL = oTrargetWeb.Site.Url.ToString().ToLower();
                string cWebRel = oTrargetWeb.Url.ToString().ToLower().Replace(cSiteURL, "");
                if (cWebRel == cSiteURL) cWebRel = "/";
                SPSecurity.RunWithElevatedPrivileges(() =>
                {
                    using (SPSite oSite = new SPSite(cSiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb(cWebRel))
                        {
                            oWeb.AllowUnsafeUpdates = true;
                            SPList oList = oWeb.Lists["ErrorList"];
                            SPListItem item = oList.Items.Add();
                            item["Title"] = cMessage;
                            item["Location"] = cLocation;
                            item["User"] = oWeb.CurrentUser;
                            oWeb.AllowUnsafeUpdates = true;
                            item.Update();
                            LogError(String.Format("{0} - {1}", cLocation, cMessage));
                        }
                    }
                });
            }
            catch
            {

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg"></param>
        public static void LogError(string msg)
        {
            WriteToSharePointLog("Error ", TraceSeverity.High, EventSeverity.Error, msg, null);
            //WriteToWindowsEventLog("Error ", TraceSeverity.High, EventSeverity.Error, msg, null);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cCategory"></param>
        /// <param name="trcSeverity"></param>
        /// <param name="evtSeverity"></param>
        /// <param name="cOutPut"></param>
        /// <param name="data"></param>
        public static void WriteToWindowsEventLog(string cCategory, TraceSeverity trcSeverity, EventSeverity evtSeverity, string cOutPut, object[] data)
        {
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
                SPDiagnosticsCategory oCat = new SPDiagnosticsCategory(cCategory, trcSeverity, evtSeverity);
                diagSvc.WriteEvent(0, oCat, evtSeverity, cOutPut, data);
            });
        }

        /// <summary>
        /// Method to write Windows event log.
        /// </summary>
        /// <param name="sSource"></param>
        /// <param name="sEvent"></param>
        public static void WriteWindowsEventLog(string cLocation, string cMessage)
        {
            WriteToWindowsEventLog("Error", TraceSeverity.High, EventSeverity.Error, cLocation, new object[] { cMessage });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cCategory"></param>
        /// <param name="trcSeverity"></param>
        /// <param name="evtSeverity"></param>
        /// <param name="cOutPut"></param>
        /// <param name="data"></param>
        public static void WriteToSharePointLog(string cCategory, TraceSeverity trcSeverity, EventSeverity evtSeverity, string cOutPut, object[] data)
        {
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
                SPDiagnosticsCategory oCat = new SPDiagnosticsCategory(cCategory, trcSeverity, evtSeverity);
                diagSvc.WriteTrace(0, oCat, trcSeverity, cOutPut, data);
            });
        }


    }
}
